﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Net.NetworkInformation;
using GlobalRadar.Language;


namespace GlobalRadar.UI
{
    public partial class AppGroupUser : PhoneApplicationPage
    {
        ApplicationBarController barControl;
        AppStatusBar myStatus = new AppStatusBar();
        string groupid;
        int owner;

        public AppGroupUser()
        {
            InitializeComponent();
            InitializeControl();

            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show(App.LangVN == true ? ResourceVN.NetworkError : ResourceEn.NetworkError);

                return;
            }
            LoadLanguage();
        }
        private void LoadLanguage()
        {
            if (App.LangVN == true)
            {
                member.Header = ResourceVN.UserMember;
                memberWaitJoin.Header = ResourceVN.UserWaitJoin;
            }
            else
            {
                member.Header = ResourceEn.UserMember;
                memberWaitJoin.Header = ResourceEn.UserWaitJoin;
            }
        }
        private void InitializeControl()
        {
            barControl = new ApplicationBarController(this.ApplicationBar);

            if (App.LangVN == true)
            {
                barControl.AddNewButton(ResourceVN.UserAcceptAll, "/icons/appbar.add.rest.png", true, ApplicationBarButton_Click);
                barControl.AddNewButton(ResourceVN.UserRemoveAll, "/icons/appbar.delete.rest.png", true, ApplicationBarButton_Click);
                barControl.AddNewButton(ResourceVN.GroupRefresh, "/icons/appbar.refresh.rest.png", true, ApplicationBarButton_Click);
            }
            else
            {
                barControl.AddNewButton(ResourceEn.UserAcceptAll, "/icons/appbar.add.rest.png", true, ApplicationBarButton_Click);
                barControl.AddNewButton(ResourceEn.UserRemoveAll, "/icons/appbar.delete.rest.png", true, ApplicationBarButton_Click);
                barControl.AddNewButton(ResourceEn.GroupRefresh, "/icons/appbar.refresh.rest.png", true, ApplicationBarButton_Click);
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            myStatus.ShowPopup(App.LangVN == true ? ResourceVN.GroupLoading : ResourceEn.GroupLoading);

            base.OnNavigatedTo(e);
            string myowner;
            if (NavigationContext.QueryString.ContainsKey("groupid"))
            {
                if (NavigationContext.QueryString.TryGetValue("groupid", out groupid))
                {
                    ReloadData();
                }
            }
            if (NavigationContext.QueryString.ContainsKey("owner"))
            {
                if (NavigationContext.QueryString.TryGetValue("owner", out myowner))
                {
                    owner = int.Parse(myowner);
                }
            }
        }
        public void ReloadData()
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                return;
            }

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            if (groupid != null && groupid != "")
            {
                client.GetListUserInGroupCompleted += (s, args) =>
                {
                    if (args.Result != null)
                        LoadDataInList(args.Result);

                    myStatus.Abort();
                };
                client.GetListUserInGroupAsync(int.Parse(groupid));
            }
        }
        public void LoadDataInList(string Content)
        {
            List<List<object>> data = Json.ParseTable(Content);

            listMember.Items.Clear();
            listWaitJoin.Items.Clear();

            foreach (List<object> row in data)
            {
                if (row.Count >= 5)
                {
                    UserInfoItem item = new UserInfoItem();
                    item.UserID = int.Parse(row[0].ToString());
                    item.Username = row[1].ToString();
                    item.Fullname = row[2].ToString();
                    item.Email = row[3].ToString();
                    item.Status = int.Parse(row[4].ToString());

                    if (item.Status == 1)
                    {
                        listMember.Items.Add(item);
                    }
                    else
                        if (item.Status == 2)
                    {
                        listWaitJoin.Items.Add(item);
                    }
                }
            }
            if(listMember.Items.Count>0)

                listMember.SelectedIndex = 0;
        }
        private void ApplicationBarButton_Click(object sender, EventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show(App.LangVN == true ? ResourceVN.NetworkError : ResourceEn.NetworkError);

                return;
            }

            ApplicationBarIconButton btn = (ApplicationBarIconButton)sender;

            string text = btn.Text.ToLower();

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            if (text == (App.LangVN == true ? ResourceVN.UserAcceptAll.ToLower() : ResourceEn.UserAcceptAll.ToLower()))
            {
                client.ChangeStatusGroupCompleted+=(s,args)=>
                {
                    MessageBox.Show(App.LangVN == true ? ResourceVN.MessageAllAccept : ResourceEn.MessageAllAccept);
                    ReloadData();
                };
                client.ChangeStatusGroupAsync(int.Parse(groupid),1, 2);
            }

            if (text == (App.LangVN == true ? ResourceVN.UserRemoveAll.ToLower(): ResourceEn.UserRemoveAll.ToLower()))
            {
                client.RemoveLinkerStatusCompleted += (s, args) =>
                {
                    MessageBox.Show(App.LangVN == true ? ResourceVN.MessageAllRemove : ResourceEn.MessageAllRemove);
                    ReloadData();
                };
                client.RemoveLinkerStatusAsync(int.Parse(groupid), 2);
            }

            if (text ==(App.LangVN==true ?ResourceVN.GroupRefresh.ToLower():ResourceEn.GroupRefresh.ToLower()))
            {
                myStatus.ShowPopup(App.LangVN == true ? ResourceVN.RefeshContent : ResourceEn.RefeshContent);
                ReloadData();
            }
        }

        private void UserPivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int i = UserPivot.SelectedIndex;
            switch (i)
            {
                case 0:
                    barControl.ShowAppBar(false);
                    break;
                case 1:
                    barControl.ShowAppBar(true);
                    if(App.LangVN==true)
                        barControl.ShowButtons(ResourceVN.UserAcceptAll,ResourceVN.UserRemoveAll,ResourceVN.GroupRefresh);
                    else
                        barControl.ShowButtons(ResourceEn.UserAcceptAll, ResourceEn.UserRemoveAll, ResourceEn.GroupRefresh);
                    break;
            }
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show(App.LangVN == true ? ResourceVN.NetworkError : ResourceEn.NetworkError);

                return;
            }

            MenuItem item = (MenuItem)sender;

            string text = item.Header.ToString().ToLower();

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            if (text == "đuổi khỏi nhóm")
            {
                if (owner != 1)
                {
                    MessageBox.Show(App.LangVN == true ? ResourceVN.UserNotLeader : ResourceEn.UserNotLeader, App.LangVN == true ?"Cảnh bảo" : "Warning!", MessageBoxButton.OK);

                    return;
                }   
                ListBoxItem listItem = this.listMember.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

                if (listItem != null)
                {
                    UserInfoItem data = listItem.Content as UserInfoItem;

                    if (data.UserID == Global.UserInfo.UserID)
                    {
                        MessageBoxResult result = MessageBox.Show(App.LangVN == true ? ResourceVN.GroupLeaderLeave : ResourceEn.GroupLeaderLeave, App.LangVN == true ? ResourceVN.LeaveGroupTitle : ResourceEn.LeaveGroupTitle, MessageBoxButton.OKCancel);

                        if (result == MessageBoxResult.OK)
                        {
                            client.RemoveGroupAsync(int.Parse(groupid));

                            client.RemoveGroupCompleted += (s, args) =>
                            {
                                if (args.Result == true)
                                {
                                    MessageBox.Show(App.LangVN == true ? ResourceVN.UserDisbanded : ResourceEn.UserDisbanded);

                                    NavigationService.Navigate(new Uri("/UI/AppGroupManager.xaml"));
                                }
                            };
                        }
                    }
                    else
                    {
                        client.RemoveLinkerCompleted += (s, args) =>
                        {
                            if (App.LangVN == true)
                                MessageBox.Show("Thành viên " + data.Username + "Đã bị đuổi");
                            else
                                MessageBox.Show(data.Username + " member has been expelled");

                            ReloadData();
                        };

                        client.RemoveLinkerAsync(int.Parse(groupid), data.UserID);
                    }
                }
            }
            if (text == "cho phép vào nhóm")
            {
                if (owner != 1)
                {
                    if (App.LangVN == true)
                        MessageBox.Show("Bạn không phải trưởng nhóm.\n", "Cảnh báo", MessageBoxButton.OK);
                    else
                        MessageBox.Show("You are not a leader.", "Warning!", MessageBoxButton.OK);
                    return;
                }
                ListBoxItem listItem = this.listWaitJoin.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

                if (listItem != null)
                {
                    UserInfoItem data = listItem.Content as UserInfoItem;

                    client.UpdateLinkerCompleted += (s, args) =>
                    {
                        if (App.LangVN == true)
                            MessageBox.Show("Thành viên " + data.Username + " đã được đồng ý vào nhóm");
                        else
                            MessageBox.Show(data.Username + " Members agreed on a group.!");

                        ReloadData();
                    };
                    client.UpdateLinkerAsync(int.Parse(groupid), data.UserID, 0, 1);                    
                }
            }
            if (text == "xóa yêu cầu tham gia")
            {
                if (owner != 1)
                {
                    if (App.LangVN == true)
                        MessageBox.Show("Bạn không phải trưởng nhóm.\n", "Cảnh báo", MessageBoxButton.OK);
                    else
                        MessageBox.Show("You are not a leader.", "Warning!", MessageBoxButton.OK);
                    return;
                }
                ListBoxItem listItem = this.listWaitJoin.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

                if (listItem != null)
                {
                    UserInfoItem data = listItem.Content as UserInfoItem;

                    client.RemoveLinkerCompleted += (s, args) =>
                    {
                        if (App.LangVN == true)
                            MessageBox.Show("Xóa thành công yêu cầu từ " + data.Username);
                        else
                            MessageBox.Show("Delete the request from " + data.Username);
                        

                        ReloadData();
                    };

                    client.RemoveLinkerAsync(int.Parse(groupid), data.UserID);
                }
            }   
        }

    }
    public class UserInfoItem
    {
        public int UserID
        {
            set;
            get;
        }
        public string Username
        {
            set;
            get;
        }
        public string Fullname
        {
            set;
            get;
        }
        public string Email
        {
            set;
            get;
        }
        public int Status
        {
            set;
            get;
        }
    }
}